package cn.com.dcsgo.library.admin.controller;

import cn.com.dcsgo.library.admin.domain.dto.PageDTO;
import cn.com.dcsgo.library.admin.domain.query.BorrowRecordPageQuery;
import cn.com.dcsgo.library.admin.domain.request.BorrowBookRequest;
import cn.com.dcsgo.library.admin.domain.request.ReturnBookRequest;
import cn.com.dcsgo.library.admin.domain.vo.BorrowRecordVO;
import cn.com.dcsgo.library.admin.response.ResponseResult;
import cn.com.dcsgo.library.admin.service.IBorrowRecordsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.io.Serializable;

/**
 * 借阅相关接口
 *
 * @author Dcsgo
 * @since 2024-09-02
 */
@RestController
@RequestMapping("/borrowRecords")
@CrossOrigin(origins = "http://localhost:8090")
@Api(tags = "借阅相关接口")
@RequiredArgsConstructor
@Slf4j
public class BorrowRecordsController {
    private final IBorrowRecordsService borrowRecordsService;

    @GetMapping("page")
    @ApiOperation("分页查询获取借阅记录")
    public ResponseResult<PageDTO<BorrowRecordVO>> queryBorrowRecords(BorrowRecordPageQuery pageQuery) {
        return ResponseResult.success(borrowRecordsService.queryBorrowRecordsByPage(pageQuery));
    }

    @PostMapping
    @ApiOperation("借阅图书")
    public ResponseResult<Long> borrowBook(@RequestBody BorrowBookRequest request) {
        try {
            return ResponseResult.success(borrowRecordsService.borrowBook(request));
        } catch (IllegalArgumentException iae) {
            return ResponseResult.fail(iae.getMessage());
        } catch (RuntimeException re) {
            log.error("borrowBook error : {}", re.getMessage());
            return ResponseResult.fail("后端错误，请联系管理人员");
        }
    }

    @PutMapping
    @ApiOperation("归还图书")
    public ResponseResult<? extends Serializable> returnBook(ReturnBookRequest request) {
        try {
            borrowRecordsService.returnBook(request);
            return ResponseResult.success();
        } catch (RuntimeException re) {
            log.error("returnBook error : {}", re.getMessage());
            return ResponseResult.fail("后端错误，请联系管理人员");
        }
    }
}
